package com.situ.ssm.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
	static SqlSessionFactory sqlSessionFactory;
	static SqlSession sqlSession;
	
	// static静态代码块在类加载后只会执行一次，而SqlSessionFactory要求项目运行起来之后
	// 只有一份，那么就可以把创建SqlSessionFactory放在static静态代码块
	static {
		//加载mybatis的核心配置文件
		InputStream inputStream = null;
		try {
			inputStream = Resources.getResourceAsStream("mybatis.xml");
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 创建SqlSessionFactory(Factory是工厂，这个工厂就是生产SqlSession的工厂)
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		sqlSession = sqlSessionFactory.openSession();
	}

	
	public static SqlSession getSqlSession() {
		return sqlSession;
	}
	
}
